package androidgames.networkgames.screens;

import java.io.IOException;
import java.util.List;

import com.badlogic.androidgames.framework.Game;

import android.util.Log;
import androidgames.networkgames.network.ConnectionHandler.OnDataReceiveListener;

public abstract class NetworkScreen extends BaseScreen implements OnDataReceiveListener, Runnable {
	public List<byte[]> dataList;
	public Thread packetHandleThread;
	public volatile boolean bRunning = false;
	public NetworkScreen(Game game) {
		super(game);
		packetHandleThread = new Thread(this);
		// TODO Auto-generated constructor stub
	}

	public abstract void onDataReceive(byte[] data) throws IOException;
	
	public synchronized void addPacket(byte[] data) {
        dataList.add(data);
    }
    
    public synchronized void removePacket(int iIndex) {
        dataList.remove(iIndex);
    }
    
    public abstract void handlePacket(byte[] data) throws Exception;
    
    public void run() {
		// TODO Auto-generated method stub
		while (bRunning) {
			if (dataList.size() > 0) {
				byte[] data = dataList.get(0);
				removePacket(0);
				try {
					handlePacket(data);
				} catch (Exception ex) {
					Log.d("Exception", ex.toString());
				}
			}
			try {
				Thread.sleep(100);
			} catch (InterruptedException ex) {
				Log.d("Exception", ex.toString());
			}
		}
	}
}
